
package bolts
import runtime._
import scala.io.Source
import scala.util.matching._

object Predef {
  implicit def Int2BoltInt(x: Int) = new BoltInt(x)
  implicit def string2BoltString(x: String) = new BoltString(x)
  implicit def regex2BoltRegex(x: Regex) = new BoltRegex(x)

  def getLinesFromFile(path: String) = new Iterator[String] {
    private val src = Source.fromPath(path)
    private val it = src.reset
    private val BOM = 0xfeff
    if (it.hasNext && it.next == BOM) src.next
    private val itr = src.getLines()
    def hasNext: Boolean = itr.hasNext
    def next: String = itr.next.stripLineEnd
  }

  def getLinesFromStdin = new Iterator[String] {
    private var line = readLine
    def hasNext: Boolean = line != null
    def next: String = { val ret = line; line = readLine; ret } 
  }

  def getLinesFromFiles(files: Array[String]) = new Iterator[String] {
    private val itf = files.elements
    private var itl = getLinesFromFile(itf.next)
    def hasNext: Boolean = {
      if (itl.hasNext) { true } else if (!itf.hasNext) { false } else {
        itl = getLinesFromFile(itf.next)
        hasNext
      }
    }
    def next: String = if (hasNext) itl.next else null
  }

  def puts(s: String) = println(s)

  def getARGF(args: Array[String]) = {
    if (args.length > 0) getLinesFromFiles(args) else getLinesFromStdin
  }
}
